import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Form, Select, Input, message, DatePicker, InputNumber, Upload, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import _ from 'loadsh'
import moment from 'moment'
import { Line, Cell, Split } from '@components/ApprovePre/Approve'
import DocLabel from '@components/ApprovePre/DocLabel'
import Text from '@components/Text'
import { decomporessListLicenseAndMobileAndBank, getUploadProps, strToNum } from '@js/tool'

const { Item } = Form
const { Option } = Select
const { TextArea } = Input

class StepOneInput extends Component {
  state = {
    dictionaries: {},
    keyTitleMap: {},
    fileList: [],
    arbitrators: []
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.instance || {}, 'currentStep.vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  // 获取枚举的字典值
  getDictionary () {
    return this.$get('/api/xapc/dictionary', {
      types: '中止类型'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 获取案件仲裁员列表
  getArbitrators () {
    const caseid = this.props.caseDetail.id
    return this.$get(`/api/xapc/case/${caseid}/arbitrator`)
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        decomporessListLicenseAndMobileAndBank(res.data)
        this.setState({
          arbitrators: res.data
        })
      })
  }

  // 初始化数据
  initData () {
    const hide = message.loading('加载中', 120)
    Promise.all([this.getDictionary(), this.getArbitrators()])
      .then(res => {
        hide()
      })
      .catch(() => hide())
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 设置id值
  changeParty (v, optionsList = []) {
    const c = this.props.formRef.current
    const result = []
    optionsList.forEach(li => {
      if (v.indexOf(li.name) !== -1) {
        result.push(li.id)
      }
    })
    c.setFieldsValue({ suspension_submittalid: result.join() })
  }

  // 改变中止天数
  changeDays (e) {
    const v = e.target.value ? Number(e.target.value) : 0
    const c = this.props.formRef.current
    const beginDatetime = c.getFieldValue(['suspension_begin_datetime'])
    c.setFieldsValue({ suspension_temp_days: v })
    if (v && beginDatetime && c) {
      this.getEndDate(Math.floor(beginDatetime / 1000), v)
    } else {
      c.setFieldsValue({ suspension_temp_end_datetime: undefined })
    }
  }

  // 改变开始时间
  changeBeginDate (e) {
    const c = this.props.formRef.current
    const days = c.getFieldValue(['suspension_temp_days'])
    c.setFieldsValue({ suspension_begin_datetime: e })
    if (e && days) {
      this.getEndDate(Math.floor(e / 1000), days)
    } else {
      c.setFieldsValue({ suspension_temp_end_datetime: undefined })
    }
  }

  // 获取结束时间
  getEndDate (beginDatetime, days) {
    const hide = message.loading('加载中', 120)
    this.$get('/api/common/days/getEndDatetime', {
      begin_datetime: beginDatetime,
      days
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      const c = this.props.formRef.current
      c.setFieldsValue({ suspension_temp_end_datetime: res.data })
    }).catch(() => hide())
  }

  // 格式化时间
  formatDate (v) {
    v = strToNum(v)
    if (v) {
      return moment(v * 1000).format('YYYY-MM-DD')
    }
    return '无'
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
    }
  }

  componentDidMount () {
    this.initData()
    this.initKeyTitleMap()
  }

  render () {
    const { keyTitleMap, dictionaries } = this.state
    const instance = this.props.instance || {}
    const currentStep = instance.currentStep || {}
    const textTemp = currentStep.text_temp || []
    const d = this.props.caseDetail
    const pList = [...d.applicants, ...d.respondents].filter(li => li.status)
    const partyList = [...pList, { id: '仲裁庭', name: '仲裁庭' }]
    const suspensionTypes = dictionaries['中止类型'] || []
    const paramFormKeyMap = {
      suspension_begin_datetime: {
        key: 'suspension_begin_datetime'
      },
      suspension_end_datetime: {
        key: 'suspension_temp_end_datetime',
        isDate: true
      },
      suspension_info: {
        key: 'suspension_info'
      }
    }
    // const beginTimeLabel = (
    //   <DocLabel label={keyTitleMap.suspension_begin_datetime} varKey='suspension_begin_datetime' textTemp={textTemp} formRef={this.props.formRef} paramFormKeyMap={paramFormKeyMap} />
    // )
    // const endTimeLabel = (
    //   <DocLabel label={keyTitleMap.suspension_temp_end_datetime} varKey='suspension_end_datetime' textTemp={textTemp} formRef={this.props.formRef} paramFormKeyMap={paramFormKeyMap} />
    // )
    const infoLabel = (
      <DocLabel label={keyTitleMap.suspension_info} varKey='suspension_info' textTemp={textTemp} formRef={this.props.formRef} paramFormKeyMap={paramFormKeyMap} />
    )
    return (
      <div>
        <Line>
          <Cell>
            <Item noStyle name='suspension_submittalid'><span /></Item>
            <Item labelCol={{ flex: '120px' }} name='suspension_submittal' label={keyTitleMap.suspension_submittal} rules={[{ required: true, message: `${keyTitleMap.suspension_submittal}不能为空` }]}>
              <Select placeholder={`请选择${keyTitleMap.suspension_submittal}`} mode='multiple' onChange={v => this.changeParty(v, partyList)}>
                {partyList.map((li, i) => <Option key={i} value={li.name}>{li.name}</Option>)}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item labelCol={{ flex: '120px' }} name='suspension_type' label={keyTitleMap.suspension_type} rules={[{ required: true, message: `${keyTitleMap.suspension_type}不能为空` }]}>
              <Select placeholder={`请选择${keyTitleMap.suspension_submittal}`}>
                {suspensionTypes.map(li => (
                  <Option key={li.title} value={li.value} title={li.title}>{li.title}</Option>
                ))}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item labelCol={{ flex: '170px' }} name='suspension_begin_datetime' label={keyTitleMap.suspension_begin_datetime} rules={[{ required: true, message: `${keyTitleMap.suspension_begin_datetime}不能为空` }]}>
              <DatePicker style={{ width: '100%' }} placeholder={`请选择${keyTitleMap.suspension_begin_datetime}`} onChange={e => this.changeBeginDate(e)} />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell>
            <Item labelCol={{ flex: '120px' }} name='suspension_temp_days' label={keyTitleMap.suspension_temp_days}>
              <InputNumber style={{ width: '100%' }} placeholder={`请输入${keyTitleMap.suspension_temp_days}`} onBlur={e => this.changeDays(e)} />
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item labelCol={{ flex: '120px' }} name='suspension_temp_end_datetime' label={keyTitleMap.suspension_temp_end_datetime}>
              <Text format={v => this.formatDate(v)} />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell style={{ width: '65%' }}>
            <Item labelCol={{ flex: '120px' }} name='suspension_info' label={infoLabel} rules={[{ required: true, message: `${keyTitleMap.suspension_info}不能为空` }]}>
              <TextArea rows={2} placeholder={`${keyTitleMap.suspension_info}不能为空`} />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell style={{ width: '65%' }}>
            <Item labelCol={{ flex: '120px' }} name='file' label={keyTitleMap.suspension_fileid}>
              <Upload {...getUploadProps.call(this, this.props.formRef)}>
                <Button disabled={this.state.fileList.length > 9}>
                  <UploadOutlined /> 上传文件
                </Button>
              </Upload>
            </Item>
          </Cell>
        </Line>
      </div>
    )
  }
}

StepOneInput.proptypes = {
  caseDetail: PropTypes.object,
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  formRef: PropTypes.object
}

StepOneInput.defaultProps = {
  caseDetail: {},
  userInfo: {},
  instance: {},
  formRef: {}
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(StepOneInput)
